/**
 * 
 * Copyright (C) 2011 Cody Stoutenburg . All rights reserved.
 *
 *       This program is free software; you can redistribute it and/or
 *       modify it under the terms of the GNU Lesser General Public License
 *       as published by the Free Software Foundation; either version 2.1
 *       of the License, or (at your option) any later version.
 *
 *       This program is distributed in the hope that it will be useful,
 *       but WITHOUT ANY WARRANTY; without even the implied warranty of
 *       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *       GNU Lesser General Public License for more details.
 *
 *       You should have received a copy of the GNU Lesser General Public License
 *       along with this program; if not, write to the Free Software
 *       Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA. 
 * 
 */
package ca.usherbrooke.tools;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * @author 
 *         http://weblogs.java.net/blog/emcmanus/archive/2007/04/cloning_java_ob.
 *         html
 * 
 */
public class Tool {
	public static <T> void removeFromTab(T[] tab, T element, T[] result) {
		int idx = 0;
		for (int i = 0; i < tab.length; ++i) {
			if (!tab[i].equals(element)) {
				result[idx] = tab[i];
				idx++;
			}
		}
	}

	public static <T> T clone(T x) {
		try {
			return cloneX(x);
		} catch (IOException e) {
			throw new IllegalArgumentException(e);
		} catch (ClassNotFoundException e) {
			throw new IllegalArgumentException(e);
		}
	}

	private static <T> T cloneX(T x) throws IOException, ClassNotFoundException {
		ByteArrayOutputStream bout = new ByteArrayOutputStream();
		ObjectOutputStream cout = new ObjectOutputStream(bout);
		cout.writeObject(x);
		cout.flush();
		cout.close();
		byte[] bytes = bout.toByteArray();
		bout.flush();
		bout.close();

		ByteArrayInputStream bin = new ByteArrayInputStream(bytes);
		ObjectInputStream cin = new ObjectInputStream(bin);

		@SuppressWarnings("unchecked")
		T clone = (T) cin.readObject();
		cin.close();
		bin.close();
		return clone;
	}
}
